import { ref, reactive, computed } from 'vue';
export default function() {
	const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true });
	let accountLoginForm = null;
	const showCreateAccount = ref(false);
	const accountBtnLoading = ref(false);
	const formData = reactive({
		username: '',
		password: '',
		passwordAgain: '',
		captcha: ''
	})
	const rules = {
		username: [{
			type: 'string',
			required: true,
			message: '请输入用户名',
			trigger: ['blur', 'change']
		}],
		password: [{
			type: 'string',
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change']
		}],
		passwordAgain: [{
			type: 'string',
			required: true,
			message: '再次输入密码',
			trigger: ['blur', 'change']
		}, {
			validator: (rule, value, callback) => {
				return formData.password === formData.passwordAgain;
			},
			message: '密码输入不一致',
			trigger: ['change']
		}]
	}
	// 登录
	function submit(form, redirectTo, captchaPopup) {
		accountLoginForm = form;
		form.validate().then(res => {
			if (showCreateAccount.value) {
				submitRegister(res, redirectTo);
			} else {
				submitLogin(res, redirectTo,captchaPopup);
			}
		}).catch(errors => {
			console.log(errors)
			uni.showToast({
				icon: 'error',
				title: '校验失败'
			})
		})
	}
	// 提交注册
	function submitRegister(res, redirectTo) {
		accountBtnLoading.value = true;
		uniIdCo.registerUser({
			username: formData.username,
			password: formData.password
		}).then(e => {
			getApp().loginSuccess({
				...e,
				showToast: false
			});
			setTimeout(() => {
				redirectTo(true);
			}, 200)
		}).catch(e => {
			uni.$uv.toast(e.message);
			console.log('登录失败：', e.message);
		}).finally(() => {
			accountBtnLoading.value = false;
		})
	}
	// 提交登录
	function submitLogin(res, redirectTo, captchaPopup) {
		accountBtnLoading.value = true;
		uniIdCo.login({
			username: formData.username,
			password: formData.password,
			captcha: formData.captcha
		}).then(e => {
			getApp().loginSuccess({
				...e,
				showToast: false
			});
			setTimeout(() => {
				redirectTo(true);
			}, 200)
		}).catch(e => {
			uni.$uv.toast(e.message);
			console.log('登录失败：', e.message);
			if (e.errCode == 'uni-id-captcha-required') {
				captchaPopup.open()
			} else {
				console.log(e.errMsg);
			}
		}).finally(() => {
			formData.captcha = ''
			accountBtnLoading.value = false;
		})
	}
	// 修改状态
	function changeShowCreate(status) {
		showCreateAccount.value = status;
		// 清除效验结果
		if (accountLoginForm) accountLoginForm.clearValidate();
	}
	return {
		showCreateAccount,
		accountLoginFormData: formData,
		accountLoginRules: rules,
		accountLoginSubmit: submit,
		changeShowCreate,
		accountBtnLoading
	}
}